package com.ztp.pc.gui.ftpclients;

import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.BorderLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.IOException;
import java.sql.SQLException;

import javax.swing.JButton;
import javax.swing.JTable;

import com.ztp.lib.client.Client;
import com.ztp.lib.client.Client.ValidationException;
import com.ztp.lib.client.SQLiteFtpClientsManager;
import net.miginfocom.swing.MigLayout;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.JCheckBox;
import javax.swing.JScrollPane;

public class FtpClientsList extends JPanel {

	private static final long serialVersionUID = -4103518860128874714L;
	private JTable table;
	private SQLiteFtpClientsManager m;
	private FtpClientsTableModel model;
	
	private JButton newBTN;
	private JButton editBTN;
	private JButton removeBTN;
	private JScrollPane scrollPane;
	
	/**
	 * Create the application.
	 * @throws SQLException 
	 * @throws ClassNotFoundException 
	 * @throws IOException 
	 */
	public FtpClientsList() throws ClassNotFoundException, SQLException, IOException {
		m = SQLiteFtpClientsManager.getInstance();
		model = new FtpClientsTableModel(m);
		initialize();
	}
	
	public Client getSelectedClient(){
		int selectedIdx = table.getSelectedRow();
		if(selectedIdx != -1){
			selectedIdx = table.convertRowIndexToModel(selectedIdx);
			return model.clients[selectedIdx];
		}
		return null;
	}

	/**
	 * Initialize the contents of the frame.
	 */
	private void initialize() {
		setLayout(new BorderLayout(0, 0));
		
		scrollPane = new JScrollPane();
		this.add(scrollPane, BorderLayout.CENTER);
		
		table = new JTable(model);
		scrollPane.setViewportView(table);
		
		
		JPanel panel_1 = new JPanel();
		this.add(panel_1, BorderLayout.SOUTH);
		
		newBTN = new JButton("New");
		newBTN.addMouseListener(mAdapter);
		panel_1.add(newBTN);
		
		editBTN = new JButton("Edit");
		editBTN.addMouseListener(mAdapter);
		panel_1.add(editBTN);
		
		removeBTN = new JButton("Remove");
		removeBTN.addMouseListener(mAdapter);
		panel_1.add(removeBTN);
		
		
	}
	
	private final MouseAdapter mAdapter = new MouseAdapter() {
		@Override
		public void mouseClicked(MouseEvent e) {
			int answer;
			if(e.getSource() == newBTN){
				ClientEditPanel cep = new ClientEditPanel();
				String [] options = new String[]{"Save", "Cancel"};
				answer = JOptionPane.showOptionDialog(null
						, cep
						, "New ftp client"
						, JOptionPane.OK_CANCEL_OPTION
						, JOptionPane.INFORMATION_MESSAGE
						, null
						, options
						, options[1]);
				if(answer == JOptionPane.OK_OPTION){
					try {
						m.addNew(cep.getResultAsClient());
					} catch (NumberFormatException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					} catch (IOException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					} catch (ValidationException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					}
				}
				try {
					model.refreshData();
				} catch (IOException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
				
			}
			else if(e.getSource() == editBTN){
				Client c = model.clients[ table.convertRowIndexToModel(table.getSelectedRow()) ];
				ClientEditPanel cep = new ClientEditPanel(c);
				
				String [] options = new String[]{"Accept", "Cancel"};
				answer = JOptionPane.showOptionDialog(null
						, cep
						, "Edit ftp client"
						, JOptionPane.OK_CANCEL_OPTION
						, JOptionPane.INFORMATION_MESSAGE
						, null
						, options
						, options[1]);
				if(answer == JOptionPane.OK_OPTION){
					try {
						m.save(cep.getResultAsClient());
					} catch (NumberFormatException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					} catch (IOException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					} catch (ValidationException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					}
					
					try {
						model.refreshData();
					} catch (IOException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					}
				}
			}
			else if(e.getSource() == removeBTN){
				Client c = getSelectedClient();
				if(c != null){
					if(JOptionPane.showConfirmDialog(null
							, "Czy napewno usunac klienta ?"
							, "Usuwanie klienta"
							, JOptionPane.OK_CANCEL_OPTION) == JOptionPane.OK_OPTION){
						try {
							m.delete(c.getId());
						} catch (IOException e1) {
							// TODO Auto-generated catch block
							e1.printStackTrace();
						}
						
						try {
							model.refreshData();
						} catch (IOException e1) {
							// TODO Auto-generated catch block
							e1.printStackTrace();
						}
					}
				}
			}
		}
	};
	
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					JFrame frame = new JFrame();
					frame.setBounds(100, 100, 373, 339);
					frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
					FtpClientsList window = new FtpClientsList();
					frame.setContentPane(window);
					frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}
	
	static class ClientEditPanel extends JPanel{
		/**
		 * 
		 */
		private static final long serialVersionUID = -4604628958842131884L;
		private JTextField hostNameTF;
		private JTextField portTF;
		private JTextField userNameTF;
		private JTextField passTF;
		private JCheckBox sslCHBX;
		Client client;
		
		/***/
		public ClientEditPanel(){
			initialise();
		}
		
		public ClientEditPanel(Client c){
			client = c;
			initialise();
			hostNameTF.setText(c.getHostName());
			userNameTF.setText(c.getUserName());
			portTF.setText(String.valueOf(c.getPort()));
			passTF.setText(c.getPassword());
			sslCHBX.setSelected(c.isSsl());
		}
		
		public Client getResultAsClient() throws NumberFormatException, ValidationException{
			if(client == null){
				return new Client(hostNameTF.getText()
						, userNameTF.getText()
						, passTF.getText()
						, Integer.valueOf(portTF.getText()).intValue()
						, sslCHBX.isSelected());
			}
			client.setHostName(hostNameTF.getText());
			client.setUserName(userNameTF.getText());
			client.setPassword(passTF.getText());
			client.setPort(Integer.valueOf(portTF.getText()).intValue());
			client.setSsl(sslCHBX.isSelected());
			return client;
		}
		
		private void initialise(){
			this.setLayout(new MigLayout("", "[74px][grow][130px]", "[20px][20px][20px][20px][23px]"));
			JLabel lblNewLabel = new JLabel("Host name:");
			this.add(lblNewLabel, "cell 0 0,alignx right,aligny center");
			
			hostNameTF = new JTextField();
			this.add(hostNameTF, "cell 2 0,growx,aligny top");
			hostNameTF.setColumns(10);
			
			JLabel lblPort = new JLabel("Port:");
			this.add(lblPort, "cell 0 1,alignx right,aligny center");
			
			portTF = new JTextField();
			portTF.setColumns(10);
			this.add(portTF, "cell 2 1,growx,aligny top");
			
			JLabel lblUsername = new JLabel("User name:");
			this.add(lblUsername, "cell 0 2,alignx right,aligny center");
			
			userNameTF = new JTextField();
			userNameTF.setColumns(10);
			this.add(userNameTF, "cell 2 2,growx,aligny top");
			
			JLabel lblPassword = new JLabel("Password:");
			this.add(lblPassword, "cell 0 3,alignx right,aligny center");
			
			passTF = new JTextField();
			passTF.setColumns(10);
			this.add(passTF, "cell 2 3,growx,aligny top");
			
			JLabel lblSsl = new JLabel("SSL:");
			this.add(lblSsl, "cell 0 4,alignx right,aligny center");
			
			sslCHBX = new JCheckBox("");
			this.add(sslCHBX, "cell 2 4,grow");
		}
		
	}
}
